//
//  HDApiManager.swift
//  HuaDaoPeifu
//
//  Created by Erickson on 16/4/7.
//  Copyright © 2016年 paiyipai. All rights reserved.
//

import Alamofire
import SVProgressHUD
import YYModel

let HDApiManagerHandler = HDApiManager.sharedInstance

class HDApiManager: NSObject {
    
    let netReachability = PYPReachability()
    
    static let sharedInstance = HDApiManager()
    fileprivate override init(){}
    var loadImageStr:String!
    
    ///banner request ——
    
    func requestBanner(_ success:@escaping ([String:AnyObject])->(),failure:@escaping (NSError)->()){
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")
        if HDAccountHandler.loginType != .notLogin {
            request(AppApi.bannerApiUrl, params: ["atk":HDAccountHandler.token!] as AnyObject, success: success, failure: failure)
        }else{
            request(AppApi.bannerApiUrl, params: nil, success: success, failure: failure)
        }
    }
    

    
    //赔付金额 —— HDPayoutDetailViewController
    func requestCaseLoan(_ caseId:String,hopeFee:String,success:@escaping ([String:AnyObject])->(),failure:@escaping (NSError)->()){
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")
        let params = ["atk":HDAccountHandler.token!,"fee":hopeFee,"case_id":caseId]
        
        request(AppApi.caseLoanApiUrl, params: params as AnyObject, success: success, failure: failure)
    }
    
    /// 保单列表 ——
    func requestPolicy(_ success: @escaping ([String:AnyObject])->(),failure:@escaping (NSError)->()){
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")
        request(AppApi.policyApiUrl, params: ["atk":HDAccountHandler.token!] as AnyObject, success: success, failure: failure)

    }
    /// 案件初始化 ——HDPayoutDetailViewController
    func requestCaseInit(_ policyno:String,success:@escaping ([String:AnyObject])->(),failure:@escaping (NSError)->()){
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")
        let params = ["policyno":policyno,"atk":HDAccountHandler.token!]
        request(AppApi.caseInitApiUrl, params: params as AnyObject, success: success, failure: failure)
    }
    
    //案件删除 ——HDPayoutDetailViewController
    func requestResubMit(_ caseid:String,success:@escaping ([String:AnyObject])->(),failure:@escaping (NSError)->()){
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")
        let params = ["case_id":caseid,"atk":HDAccountHandler.token!]
        request(AppApi.resubmitApiUrl, params: params as AnyObject, success: success, failure: failure)
    }
    ///提交图片 ——HDPayoutDetailViewController
    func requestCaseUpload(_ repModel:HDCaseUploadRepModel,success:@escaping (_ response :[String:AnyObject])->(),failure:@escaping (_ error :Error)->()){
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")

        let params = ["policyno":repModel.policyno,"datatype":repModel.datatype,"case_id":repModel.case_id,"imgnumber":repModel.imgnumber,"imgtotal":repModel.imgtotal,"atk":HDAccountHandler.token!]
        
        printRequestLog(AppApi.caseUploadApiUrl, params: params as AnyObject)
        requestUploadImage(loadImageStr, image: repModel.img, success: success, failure: failure)
        
        
    }
    /// —— ↑
    func requestUploadImage(_ urlStr:String,image:UIImage,success:@escaping ([String:AnyObject])->(),failure:@escaping (Error)->()){
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")
        let headers = ["content-type":"multipart/form-data"]

        Alamofire.upload(multipartFormData: { multipartFormData in
            
            multipartFormData.append(UIImageJPEGRepresentation(image, 0.7)!, withName:  "img", fileName:  "img.jpg", mimeType: "image/jpeg")
            
        }, to:urlStr,
           headers: headers,
           encodingCompletion: { result in
            switch result {
            case .success(let upload, _, _):
                
//                upload.uploadProgress(closure: { (progress) in
//                    //Print progress
//                })
                
                upload.responseJSON { response in
                    if let value = response.result.value as? [String: AnyObject]{
                        success(value)
                    }
                }
                
            case .failure( _): break
                //print encodingError.description
            }
        }
        )
        
}
    
    /**
     修改手机号
     */
    
    func requestUpdatePhone(_ phoneModel:HDUpdatePhone,success:@escaping ([String:AnyObject])->(),failure:@escaping (NSError)->()) {
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")
        let params = ["newphone":phoneModel.newphone,"code":phoneModel.code,"atk":phoneModel.atk]
        
        request(BaseApi.updatePhoneApiUrl, params: params as AnyObject?, success: success, failure: failure)
    }

    
    /**
     验证码
     */
    func requestAuthcode(_ authCode:PYPAuthcode,success:@escaping ([String:AnyObject])->(),failure:@escaping (NSError)->()) {
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")
        let params = ["phone":authCode.phone,"tms":authCode.tms,"reqmode":authCode.reqmode]
        request(RegistApi.authCodeApiUrl, params: params as AnyObject, success: success, failure: failure)
    }
    
    
    /**
     验证码认证
     */
    func requestCkauthcode(_ certCode:PYPCkauthcode,success:@escaping ([String:AnyObject])->(),failure:@escaping (NSError)->()) {
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")
        let params = ["phone":certCode.phone,"code":certCode.code,"reqmode":certCode.reqmode]
        
        request(RegistApi.cKAuthCodeApiUrl, params: params as AnyObject, success: success, failure: failure)
    }
    
    /**
     注册
     */
    func requestReg(_ reg:PYPReg , success:@escaping ([String:AnyObject])->(),failure:@escaping (NSError)->()) {
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")
        request(BaseApi.registerApiUrl, params: reg.toDict() as AnyObject, success: success, failure: failure)
    }
    
    
    /**
     登录
     */
    func requestLogin(_ login:PYPLogin ,success:@escaping ([String:AnyObject])->(),failure:@escaping (NSError)->()) {
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")
        let params = ["phone":login.phone,"ptxt":login.ptxt,"did":login.did]
        request(BaseApi.userLoginApiUrl, params: params as AnyObject, success: success, failure: failure)
    }
    
    
    /**
     重置密码
     */
    func requestRepwd(_ repwd:PYPRepwd ,success:@escaping ([String:AnyObject])->(),failure:@escaping (NSError)->()) {
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")
        let params = ["phone":repwd.phone,"newptxt":repwd.newptxt,"code":repwd.code]
        request(BaseApi.repwdApiUrl, params: params as AnyObject, success: success, failure: failure)
    }
    
    /**
     反馈
     */
    func requestFeedback(_ feedback:PYPFeedback ,success:@escaping ([String:AnyObject])->(),failure:@escaping (NSError)->()) {
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")
        var params = ["phone":feedback.phone,"content":feedback.content]
        if let token = HDAccountHandler.token {
            params["atk"] = token
            
        }
        request(BaseApi.feedbackApiUrl, params: params as AnyObject, success: success, failure: failure)
    }
    
    /**
     个人信息
     */
    func requestUserMessage(_ success:@escaping ([String:AnyObject])->(),failure:@escaping (NSError)->()) {
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")
        let params = ["atk": HDAccountHandler.token!]
        print("BaseApi.userdApiUrl = \(BaseApi.userMessageApiUrl)")
        request(BaseApi.userMessageApiUrl, params: params as AnyObject, success:success, failure: failure)
    }
    
    /*
     *银行信息
     */
    func requestBankInfo(_ success:@escaping ([String:AnyObject])->(),failure:@escaping (NSError)->()){
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")
        let params = ["atk": HDAccountHandler.token!]
        request(BaseApi.bankInfoApiUrl, params: params as AnyObject, success: success, failure: failure)
    }
    
    /*
     *投保机构
     */
    func requestInsurance(_ success:@escaping ([String:AnyObject])->(),failure:@escaping (NSError)->()){
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")
        let params = ["atk": HDAccountHandler.token!]
        request(BaseApi.insuranceApiUrl, params: params as AnyObject, success: success, failure: failure)
    }
    /**
     修改密码 !!!!!!!!!!!!注意修改密码的接口必须要改，目前是明文传输
     */
    func requestEditpwd(_ token :String, oldptxt: String, newptxt: String, success:@escaping ([String:AnyObject])->(),failure:@escaping (NSError)->()) {
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")
        let params = ["atk": token, "oldptxt": oldptxt, "newptxt": newptxt]
        request(BaseApi.editpwdApiUrl, params: params as AnyObject, success: success, failure: failure)
    }
    
    /**
     上传头像
     */
    
    
    func requestUploadUserHeadImg(_ token: String, headimg: UIImage, success:@escaping (NSDictionary)->(),failure:@escaping (Error)->()) {
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")
        let imgName = "headimg" //API规定的
        uploadImage(BaseApi.userEditHeadApiUrl, token: token, headimg: headimg, imgName: imgName, success: success,failure:failure)
    }

    
    func requestArchives(_ success:@escaping ([String:AnyObject])->(),failure:@escaping (Error)->()) {
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")
        let params = ["atk":HDAccountHandler.token!]
        request(AppApi.archivesApiUrl, params: params as AnyObject, success: success, failure: failure)
        
        
    }
    //档案详情
    func requestArchivesDetail(_ model:HDArchivesModel,success:@escaping ([String:AnyObject])->(),failure:@escaping (Error)->()){
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")
        let params = ["atk":HDAccountHandler.token!,"policyno":model.policyno,"case_id":model.case_id] as [String : Any]
        request(AppApi.archivesDetailApiUrl, params: params as AnyObject, success: success, failure: failure)
        
    }
    
    /**
     小红点
     */
    func requestCaseNumber(_ success:@escaping ([String:AnyObject])->(),failure:@escaping (Error)->()) {
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")
        let params = ["atk":HDAccountHandler.token!]
        request(AppApi.caseNumberApiUrl, params: params as AnyObject, success: success, failure: failure)

    }
    
    
    
    /// 下载通知书
    
    func requestDownloadNotice(_ urlStr:String)->Void{
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")
        
        let destination: DownloadRequest.DownloadFileDestination = { _, _ in
            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            let lossArray = urlStr.components(separatedBy: "/")
            let  pdfName = lossArray.last!
            let fileURL = documentsURL.appendingPathComponent(pdfName)

    
            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
        }
        
        Alamofire.download(urlStr,to:destination).response { response in
            print(response)
            
            
        }
        
        
    }
        
        
    

    fileprivate func uploadImage(_ url: String, token: String, headimg: UIImage, imgName: String, success:@escaping (NSDictionary)->(),failure:@escaping (Error)->()) {
        print("++++++++++++++++++++++++++++++++++++++++++++++++++\(#function)")
        Alamofire.upload(multipartFormData: { (multipartFormData) in
            multipartFormData.append(UIImageJPEGRepresentation(headimg, 0.6)!, withName:  imgName, fileName:  "\(imgName).jpg", mimeType: "\(imgName)/jpg")
            
        }, to:"\(url)?atk=\(token)")
        { (result) in
            switch result {
            case .success(let upload, _, _):
                
                upload.uploadProgress(closure: { (progress) in
                    //Print progress
                })
                
                upload.responseJSON { response in
                    //print response.result
                }
                
            case .failure( _): break
                //print encodingError.description
            }
        }

    }
    
    

    
    
    
    
    fileprivate func request(_ url:String ,params:AnyObject? ,success:@escaping ([String:AnyObject])->(),failure:@escaping (NSError)->()){
        #if DEBUG
            printRequestLog(url, params: params)
        #else
        #endif
        if netReachability.status == .noReachable {
            debugPrint("网络不通")
            return
        }
        
        Alamofire.request(url,method:.post,parameters: params as? Dictionary).responseJSON() { response  in
            let str = NSString(data: response.data!, encoding: String.Encoding.utf8.rawValue)!
            //debugPrint(response)
            
            switch response.result{
            case .success:
                
                if let value = response.result.value as? [String:AnyObject] {
                    success(value)
                }
                
            case .failure(let error):
                failure(error as NSError)
                SVProgressHUD.showError("服务器出小差了，请稍后重试")
            }
        }
    }
    
    
    /**
     打印 URL 和 参数
     */
    fileprivate func printRequestLog(_ url:String ,params:AnyObject?) {
        //debugPrint(url,params)
        var parString = ""
        var paramsString = ""
        var paramsStrings = ""
        if let pars = params {
            //            print(pars)
            for (key,value) in pars as! Dictionary<String,String> {
                parString = key + "=" + value + "&"
                paramsString += parString
                
            }
            
            let newStr = paramsString as NSString
            let parSt = newStr.substring(to: newStr.length-1)
            paramsStrings = parSt
        }
        // let urlSt = url as NSString
        // let subSt = urlSt.range(of: "/apiv").location
        
        // let urlSub = try urlSt.substring(from: subSt+7)
        
        // debugPrint("🍎" + urlSt + "🍎")
        debugPrint("🤔" )
        debugPrint(url + "?" + paramsStrings)
        loadImageStr = url + "?" + paramsStrings
        
    }
    
    // MARK: - 下面是新的接口方法 Jeremy
    
    /// 请求注册验证码
    func requestRegAuthcode(_ authCode:PYPAuthcode,_ completionHandler:@escaping (HDApiResult?)->()) {
        let params = ["phone":authCode.phone,"tms":authCode.tms,"reqmode":authCode.reqmode]
        post(RegistApi.authCodeApiUrl, params: params as AnyObject) { (result) in
            completionHandler(result)
        }
    }
    
    /// 校验验证码
    func requestCKAuthcode(_ authCode:PYPCkauthcode,_ completionHandler:@escaping (HDApiResult?)->()) {
        let params = ["phone":authCode.phone,"code":authCode.code,"reqmode":authCode.reqmode]
        post(RegistApi.cKAuthCodeApiUrl, params: params as AnyObject) { (result) in
            completionHandler(result)
        }
    }
    
    /// 注册
    func requestReg_new(_ reg:PYPReg , completionHandler:@escaping (HDApiResult?)->()) {
        
        post(RegistApi.registUserApiUrl, params: reg.toDict() as AnyObject, completionHandler: completionHandler)
    }
    
    /// 个人登录 v2
    func requestPersonalLogin_new(_ login:PYPLogin ,_ completionHandler:@escaping (HDApiResult?) -> ()) {
        
        post(RegistApi.loginApiUrl, params: login.toDict() as AnyObject, completionHandler: completionHandler)
    }
    
    /// 请求个人投保机构列表 v2
    func requestInsurance(_ completionHandler:@escaping (HDApiResult?)->()) {
        tokenPost(RegistApi.userInsurancesApiUrl, params: nil, completionHandler: completionHandler)
    }
    
    
    /// 验证团队用户登录所选机构的有效性 v2
    func requestGroupLogin(insuranceNo:String!, completionHandler:@escaping (HDApiResult?)->()) {
        guard let param = insuranceNo else {
            return
        }
        tokenPost(RegistApi.verifyUserInsurancesApiUrl, params: ["insuranceno":param] as AnyObject, completionHandler: completionHandler)
    }
    
    /// 请求个人信息（默认带参数token） v2
    func requestUserInfo(_ completionHandler:@escaping(HDAccountInfo?)->()) {
        tokenPost(RegistApi.requestUserInfoApiUrl, params: nil) {[unowned self] (result:HDApiResult?) in
            self.dealWithDictionaryResponce(result, completionHandler)
        }
    }
    
    /// 获取用户积分
    func requestUserIntegral(_ completionHandler:@escaping (Int?)->()) {
        tokenPost(IndividualCenterApi.requestUserIntegralApiUrl, params: nil) { (result:HDApiResult?) in
            guard let result = result else {
                completionHandler(nil)
                return
            }
            if (result.status == .Success){
                guard let data = result.data
                else {
                        completionHandler(nil)
                        return
                }
                
                completionHandler(data as? Int)
            }else{
                completionHandler(nil)
            }
        }
    }
    
    /// 获取用户积分明细
    func requestUserIntegralList(_ completionHandler:@escaping ([HDIntegralDetail]?)->()) {
        
        tokenPost(IndividualCenterApi.requestUserIntegralDetailApiUrl, params: nil) {[unowned self] (result:HDApiResult?) in
            self.dealWithArrayResponce(result, completionHandler)
        }
    }
    
    
    /// 获取个人中心设置页面数据
    func requestUserSettingInfo(_ completionHandler:@escaping (HDAccountInfo?)->()) {
        tokenPost(IndividualCenterApi.requestUserSettingInfoApiUrl, params: nil) {[unowned self] (result:HDApiResult?) in
            self.dealWithDictionaryResponce(result, completionHandler)
        }
    }
    
    /// 获取用户银行信息
    func requestBankInfo(_ completionHandler:@escaping(HDApiResult?)->()) {
        tokenPost(IndividualCenterApi.requestBanInfoApiUrl, params: nil) {(result:HDApiResult?) in
            completionHandler(result)
        }
    }
    
    /// 获取跟踪的保单数据
    func requestPolicylist(_ completionHandler:@escaping(HDFollowedPolicyListModel?)->()){
        tokenPost(BusinessApi.policylistApiUrl, params: nil) {[unowned self] (result:HDApiResult?) in
            self.dealWithDictionaryResponce(result, completionHandler)
        }
    }
    /// 获取保单信息数据
    func requestPolicyInfo(caseID case_id:String , _ completionHandler:@escaping (HDPolicyModel?)->()) {
        tokenPost(BusinessApi.policyInfoApiUrl, params: ["case_id":case_id]) { [unowned self] (result:HDApiResult?) in
            self.dealWithDictionaryResponce(result, completionHandler)
        }
    }
    /// 获取保单info_id
    func requestPolicyInfoID(caseID case_id:String , _ completionHandler:@escaping (HDApiResult?)->()) {
        tokenPost(BusinessApi.policyInfoIdApiUrl, params: ["case_id":case_id]) {[unowned self] (result:HDApiResult?) in
            guard let result = result else{
                completionHandler(nil)
                return
            }
            if result.status == .Success{
                completionHandler(result)
            }else{
                completionHandler(nil)
            }
        }
    }
    /// 获取保单历史信息
    func requestPolicyLog(caseID case_id:String , _ completionHandler:@escaping ([HDPolicyLogModel]?)->()) {
        tokenPost(BusinessApi.policyLogsApiUrl, params: ["case_id":case_id]) { [unowned self] (result:HDApiResult?) in
            self.dealWithArrayResponce(result, completionHandler)
        }
    }
    /// 获取保单账单列表
    func requestPolicyBillList(caseID case_id:String , _ completionHandler:@escaping (_ payModels: [HDPolicyBillModel]?,_ noPayModels: [HDPolicyBillModel]?)->()) {
        tokenPost(BusinessApi.policyBillsApiUrl, params: ["case_id":case_id]) { (result:HDApiResult?) in
            guard let result = result else {
                completionHandler(nil,nil)
                return
            }
            
            if result.status == .Success {
                
                if let pay = result.data {
                    
                    if let dataDicts = try? pay as! [String:Any] {
                        var paymodels = [HDPolicyBillModel]()
                        var nopaymodels = [HDPolicyBillModel]()
                        
                        if let list = try? dataDicts["pay"] as? [Any]{
                        
                            for dict in list ?? [] {
                                if let model = HDPolicyBillModel.yy_model(withJSON: dict) {
                                    paymodels.append(model)
                                }
                            }
                        }
                        
                        if let list = try? dataDicts["nopay"] as? [Any]{
                            
                            for dict in list ?? [] {
                                if let model = HDPolicyBillModel.yy_model(withJSON: dict) {
                                    nopaymodels.append(model)
                                }
                            }
                        }
                        
                        completionHandler(paymodels,nopaymodels)
                        
                    }else {
                        completionHandler(nil,nil)
                    }
                }else{
                    completionHandler(nil,nil)
                }
            }else{
                print(result.msg)
                completionHandler(nil,nil)
            }
        }
    }
    /// 获取保单被拒绝理由
    func requestRefuseReason(caseID case_id:String , _ completionHandler:@escaping (String?)->()) {
        tokenPost(BusinessApi.policyBillsApiUrl, params: ["case_id":case_id]) {[unowned self] (result:HDApiResult?) in
            self.dealWithStringResponce(result, completionHandler)
        }
    }
    
    /// 请求首页广告列表
    func requestBannerList(_ completionHandler:@escaping ([HDHomeBannerModel]?)->()) {
        if HDAccountHandler.userType != .notLogin {
            tokenPost(BusinessApi.bannerListApiUrl, params: nil) {[unowned self] (result:HDApiResult?) in
                self.dealWithArrayResponce(result, completionHandler)
            }
        }else{
            post(BusinessApi.bannerListApiUrl, params: nil) {[unowned self] (result:HDApiResult?) in
                self.dealWithArrayResponce(result, completionHandler)
            }
        }
    }
    /// 请求声明数据
    func requestAnnouncementList(_ completionHandler:@escaping ([[String:Any]]?)->()) {
        
        if HDAccountHandler.userType != .notLogin {
            tokenPost(BusinessApi.announcementListApiUrl, params: nil) {[unowned self] (result:HDApiResult?) in
                self.dealWithDictArrayResponce(result, completionHandler)
            }
        }else{
            post(BusinessApi.announcementListApiUrl, params: nil) {[unowned self] (result:HDApiResult?) in
                self.dealWithDictArrayResponce(result, completionHandler)
            }
        }
    }
    
    /// 首页请求保单列表数据
    func requestHomePolicyList(_ completionHandler:@escaping ([HDHomePolicyModel]?)->()) {
        var param = [String:Any]()
        if let insuranceno = HDAccountHandler.insuranceno {
            param["insuranceno"] = insuranceno
        }
        
        if let login_type = HDAccountHandler.userType?.rawValue {
            param["login_type"] = login_type
        }
        
        tokenPost(BusinessApi.homePolicyListApiUrl, params: param) {[unowned self] (result:HDApiResult?) in
            self.dealWithArrayResponce(result, completionHandler)
        }
    }
    /// 请求手册数据
    func requestManuals(_ completionHandler:@escaping ([HDManualModel]?)->()) {
        if HDAccountHandler.userType != .notLogin {
            tokenPost(BusinessApi.manualsApiUrl, params: nil) {[unowned self] (result:HDApiResult?) in
                self.dealWithArrayResponce(result, completionHandler)
            }
        }else{
            post(BusinessApi.manualsApiUrl, params: nil) {[unowned self] (result:HDApiResult?) in
                self.dealWithArrayResponce(result, completionHandler)
            }
        }
    }
    /// 请求被保人名单
    func requestRecognizeeList(_ completionHandler:@escaping ([HDRecognizeeModel]?)->()) {
        tokenPost(BusinessApi.recognizeeApiUrl, params: nil) {[unowned self] (result:HDApiResult?) in
            self.dealWithArrayResponce(result, completionHandler)
        }
    }
    /// 删除被保人
    func deleteRecognizee(_ id:String,_ completionHandler:@escaping (HDApiResult?)->()) {
        
        tokenPost(BusinessApi.deleteRecognizeeApi, params: ["info_id":id]) {(result:HDApiResult?) in
            completionHandler(result ?? nil)
        }
    }
    
    /// 新增被保人
    func addRecognizee(_ param:HDRecognizeeModel,_ completionHandler:@escaping (HDApiResult?)->()) {
        let param = param.yy_modelToJSONObject() as! Dictionary<String, Any>
        tokenPost(BusinessApi.addRecognizeeApi, params: param) { (result:HDApiResult?) in
            completionHandler(result ?? nil)
        }
    }
    
    /// 被保人是否包含本人
    func existRecognizeeSelf(_ completionHandler:@escaping (HDApiResult?)->()) {
        tokenPost(BusinessApi.recognizeeExistSelf, params: nil) { (result:HDApiResult?) in
            completionHandler(result)
        }
    }
    
    /// 获取本人被保人基本信息
    func requestOrzinfo(_ completionHandler:@escaping (HDOrzinfoModel?)->()) {
        tokenPost(BusinessApi.orzinfoApi, params: nil) {[unowned self] (result:HDApiResult?) in
        self.dealWithDictionaryResponce(result, completionHandler)
        }
    }
    
    /// 判断当前被保人是否是本人
    func requestCurrentRecognizeeIsSelf(_ info_id:String,_ completionHandler:@escaping (HDApiResult?)->()) {
        tokenPost(BusinessApi.selfinfoApi, params: ["info_id":info_id]) { (result) in
            completionHandler(result)
        }
    }
    
    /// 保单初始化 
    func requestInitCase(_ policyno:String,_ completionHandler:@escaping (HDCaseModel?)->()){
        tokenPost(BusinessApi.caseinitApi, params: ["policyno":policyno]) { (result) in
            self.dealWithDictionaryResponce(result, completionHandler)
        }
    }
    /// 获取案件默认被保人信息
    func requestDefaultRecognizee(_ info_id:String,_ case_id:String,_ completionHandler:@escaping (HDApiResult?)->()) {
        tokenPost(BusinessApi.caseDefaultUserInfo, params: ["info_id":info_id,"case_id":case_id]) { (result) in
            if let result = result,
            let data = result.data{
                result.data = HDRecognizeeModel.yy_model(withJSON: data)
            }
            
            completionHandler(result)
        }
    }
    
    /// 新增partone
    func infoAddPartone(_ case_id:String,_ info_id:String,_ completionHandler:@escaping (HDApiResult?)->()) {
        tokenPost(BusinessApi.infoAddPartone, params: ["info_id":info_id,"case_id":case_id]) { (result) in
            completionHandler(result)
        }
    }
    
    // 查询parttwo
    func requestParttwo(_ case_id:String,_ info_id:String,_ completionHandler:@escaping (HDRecognizeeModel?)->()) {
        tokenPost(BusinessApi.requestParttwo, params: ["info_id":info_id,"case_id":case_id]) { (result) in
            self.dealWithDictionaryResponce(result, completionHandler)
        }
    }
    
    /// 更新parttwo
    func updateParttwo(_ case_id:String,_ info_id:String,_ parttwo:HDParttwoModel,_ completionHandler:@escaping (HDApiResult?)->()) {
        
        let param = parttwo.yy_modelToJSONObject() as! [String:Any]
        tokenPost(BusinessApi.updateParttwo, params: ["case_id":case_id,"info_id":info_id,"parttwo":param]) { (result) in
            completionHandler(result)
        }
    }
    
    /// 请求partthree的证件照
    func requestPartthreeIdPic(_ info_id:String, _ case_id:String,_ completionHandler:@escaping ([UIImage]?)->()) {
        tokenPost(BusinessApi.requestPartoneIdPic, params: ["case_di":case_id,"info_id":info_id]) { (result) in
            guard let result = result,
            let data = result.data
            else {
                completionHandler(nil)
                return
            }
            

            
            if result.status == .Success {
                
                var dict : [String:String]?
                do {
                    dict = try data as? [String:String]
                }catch {
                    
                    print("！！！！！处理请求返回值时捕获异常，url：\(BusinessApi.requestPartoneIdPic)")
                }
                var images = [UIImage]()
                
                if let dict = dict {
                    for (_,n) in dict.enumerated(){
                        if n.value.lengthOfBytes(using: String.Encoding.utf8) > 0 {

                            var index : String.Index
                            if let idx = n.value.index(of: ",") {
                                index = String.Index(encodedOffset: idx.encodedOffset + 1)
                            }else {
                                index = String.Index.init(encodedOffset: 0)
                            }

                            let imageString = n.value.substring(from: index)
                            if let imageData = Data(base64Encoded: imageString),
                                let image = UIImage(data: imageData) {
                                images.append(image)
                            }
                        }
                    }
                    completionHandler(images)
                }else{
                    completionHandler(images)
                }
            }else{
                completionHandler(nil)
            }
        }
    }
    
    /// 上传案件图片 __
    func uploadCaseImage(_ img:String,_ imgtotal:String,_ datatype:String,_ imgnumber:String,_ case_id:String,_ policyno:String,_ completionHandler:@escaping (HDApiResult?)->()) {
        tokenPost(BusinessApi.uploadCaseImage, params: ["img":img,"imgtotal":imgtotal,"datatype":datatype,"imgnumber":imgnumber,"case_id":case_id,"policyno":policyno]) { (result) in
            completionHandler(result)
        }
    }
    
    /// 请求档案附件图片
    func requestArchivesImages(_ case_id:String,_ policyno:String,_ completionHandler:@escaping ([String:Any]?)->()) {
        
        tokenPost(BusinessApi.requestArchivesDetail, params: ["case_id":case_id,"policyno":policyno]) { (result) in
            guard let result = result else {
                completionHandler(nil)
                return
            }
            
            if result.status == .Success {
                
                if let data = result.data,
                    let dict = try? data as! [String:Any],
                    let archives = dict["datatype_list"]{
                        completionHandler(archives as? [String : Any])
                }else{
                    print("\(#function) ___ 数据解析错误")
                    completionHandler(nil)
                }
            }else {
                completionHandler(nil)
            }
        }
    }
    /// 获取电子申请表
    func requestApplicationForm(_ info_id : String,_ case_id : String,_ completionHandler:@escaping (HDApplicationFormModel?)->()) {
        tokenPost(BusinessApi.requestApplicationForm, params: ["info_id":info_id,"case_id":case_id]) { (result) in
            self.dealWithDictionaryResponce(result, completionHandler)
        }
    }
    
    
    
    
     //补充附件上传图片
    func requestUploadSupplyImages(_ img:String,_ datatype:String,_ case_id:String,_ imgtotal:String,_ imgnumber:String,_ policyno:String,_ completionHandler:@escaping (String?)->()) {
        tokenPost(BusinessApi.requestUploadImages, params: ["img":img,"imgtotal":imgtotal,"datatype":datatype,"imgnumber":imgnumber,"case_id":case_id,"policyno":policyno]) { (result) in
            guard let result = result else{
                completionHandler(nil)
                return
            }
            if result.status == .Success{
                completionHandler("success")
            }else{
                 completionHandler(nil)
            }
            
        }
        
    }
    //补充附件放弃理赔
    func requstGiveUpSupplyImages(_ case_id:String,_ policyno:String,_ completionHandler:@escaping (String?)->()) {
        tokenPost(BusinessApi.requestSupplyGiveUp, params: ["case_id":case_id,"policyno":policyno]) { (result) in
            guard let result = result else{
                completionHandler(nil)
                return
            }
            if result.status == .Success{
                completionHandler("success")
            }else{
                completionHandler(nil)
            }
            
        }
        
    }
    //案件申诉记录
    func requstArchiveRecord(_ case_id:String,_  completionHandler:@escaping ([HDAppealLogModel]?)->()) {
        tokenPost(BusinessApi.requestArchiveRecord, params:  ["case_id":case_id]) { (result) in
            self.dealWithArrayResponce(result, completionHandler)
        }
    }
    // 删除案件
    func requstArchieveDelete(_ case_id:String,_ completionHandler:@escaping (HDApiResult?)->()) {
        tokenPost(BusinessApi.requestArchiveDelete, params: ["case_id":case_id]) { (result) in
            guard let result = result else{
                completionHandler(nil)
                return
            }
            if result.status == .Success{
                completionHandler(result)
            }else{
                completionHandler(nil)
            }
            
        }
        
    }
    //案件账单记录
    func requstArchiveBill(_ case_id:String,_  completionHandler:@escaping (String?)->()) {
        tokenPost(BusinessApi.requestArchiveBill, params:  ["case_id":case_id]) { (result) in
            guard let result = result else{
                completionHandler(nil)
                return
            }
            if result.status == .Success{
                completionHandler("success")
            }else{
                completionHandler(nil)
            }
        }
    }
    
    /// 放弃案件
    func closeCase(_ case_id: String,_ completionHandler:@escaping (HDApiResult?)->()) {
        tokenPost(BusinessApi.closeCase, params: ["case_id":case_id]) { (result) in
            guard let result = result else{
                completionHandler(nil)
                return
            }
            if result.status == .Success{
                completionHandler(result)
            }else{
                completionHandler(nil)
            }
        }
    }
    
    fileprivate func dealWithDictArrayResponce(_ result:HDApiResult?,_ completionHandler:@escaping([[String:Any]]?)->()){
        guard let result = result else {
            completionHandler(nil)
            return
        }
        if (result.status == .Success){
            guard let data = result.data
                else {
                    completionHandler(nil)
                    return
            }
            
            completionHandler(data as? [[String : Any]])
        }else{
            completionHandler(nil)
        }
    }
    
    
    fileprivate func dealWithStringResponce(_ result:HDApiResult?,_ completionHandler:@escaping(String?)->()){
        guard let result = result else {
            completionHandler(nil)
            return
        }
        if (result.status == .Success){
            guard let data = result.data
                else {
                    completionHandler(nil)
                    return
            }
            
            completionHandler(data as? String)
        }else{
            completionHandler(nil)
        }
    }
    
    fileprivate func dealWithArrayResponce<T:NSObject>(_ result:HDApiResult?,_ completionHandler:@escaping([T]?)->()){
        guard let result = result else {
            completionHandler(nil)
            return
        }
        if (result.status == .Success){
            guard let data = result.data,
                let list = NSArray.yy_modelArray(with: T.self, json: data)
                else {
                    completionHandler(nil)
                    return
            }
            
            completionHandler(list as? [T])
        }else{
            completionHandler(nil)
        }
    }
    
    fileprivate func dealWithDictionaryResponce<T:NSObject>(_ result:HDApiResult?,_ completionHandler:@escaping(T?)->()){
        guard let result = result else {
            completionHandler(nil)
            return
        }
        if (result.status == .Success){
            guard let data = result.data,
                let model = T.yy_model(withJSON: data)
                else {
                    completionHandler(nil)
                    return
            }
            
            completionHandler(model)
        }else{
            completionHandler(nil)
        }
    }
    
    
    /// 以base64方式上传图片
    func uploadBase64Image(_ urlString:String,_ key:String,_ image:UIImage,_ completionHandler:@escaping (HDApiResult?)->()){
        
        guard  let imageData = UIImagePNGRepresentation(image)
            else {
                return
        }
        let base64String = imageData.base64EncodedString()
        
        post(urlString, params: [key:base64String] as AnyObject) { (result) in
            completionHandler(result)
        }
    }
    
    fileprivate func post(_ url:String ,params:AnyObject? ,completionHandler:@escaping (HDApiResult?)->()){
        #if DEBUG
        //printRequestLog(url, params: params)
        #else
        #endif
        if netReachability.status == .noReachable {
            debugPrint("网络不通")
            return
        }
        
//        print(url)
//        print("-------------->\(params)")
        Alamofire.request(url,method:.post,parameters: params as? Dictionary).responseJSON() { response  in
            // debugPrint(response)
            switch response.result{
            case .success:
                if let value = response.result.value as? [String:AnyObject], let result = HDApiResult.yy_model(withJSON: value) {
                    completionHandler(result)
                }else{
                    completionHandler(nil)
                }
                
            case .failure(let error):
                // failure(error as NSError)
                debugPrint("crash in sending networking request  error:\(error)")
                SVProgressHUD.showError("服务器开小差了，请稍后重试")
                completionHandler(nil)
            }
        }
    }
    
    /// 带token的请求
    func tokenPost(_ url:String ,params:Any? ,completionHandler:@escaping (HDApiResult?)->()){
        
        guard let token = HDAccountHandler.token else {
            completionHandler(nil)
            return
        }
        
        var p:[String:AnyObject] = ["atk":token as AnyObject]
        if params != nil {
            p.merge(params as! [String : AnyObject]) { (o, n) -> AnyObject in
                return o
            }
        }
        
        post(url, params: p as AnyObject, completionHandler: completionHandler)
        
    }
    
}


